package com.fengli.task.service.serviceImpl;

import com.fengli.task.dao.UserMapper;
import com.fengli.task.entity.UserEntity;
import com.fengli.task.service.UserService;
import com.fengli.task.uitl.ApplicationUtil;
import com.fengli.task.uitl.auth.bean.CustomUserDetails;
import com.fengli.task.uitl.exception.CanNotFindDataException;
import com.fengli.task.uitl.exception.InsertDataToDatabaseException;
import com.fengli.task.uitl.exception.SelectDataFromDatabaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: 该接口用于实现UserService接口
 * @Author: fengli
 * @Date 4/19/19 1:20 PM
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    //用于访问数据库
    private UserMapper userDao;

    @Override
    public boolean matchUser(String email, String password) {
        UserEntity userEntity;
        try {
            userEntity = userDao.queryUser(email, ApplicationUtil.md5(password));
        } catch (Exception e) {
            throw new SelectDataFromDatabaseException("查询用户失败");
        }
        if (userEntity != null) {
            return true;
        }
        return false;
    }


    @Override
    public boolean addUser(String email, String password) {
        UserEntity userEntity = new UserEntity();
        userEntity.setEmail(email);
        userEntity.setPassword(ApplicationUtil.md5(password));
        userEntity.setId(ApplicationUtil.getUUID());
        try {
            userDao.insert(userEntity);
        }catch (Exception e){
            throw new InsertDataToDatabaseException("添加用户异常，该邮箱可能已经被注册或"+e.getMessage());
        }
        return true;
    }

    @Override
    public UserEntity findUser(String id) {
        UserEntity userEntity= userDao.queryUserById(id);
        if(userEntity == null){
            /* 跑找不到用户异常*/
            throw new CanNotFindDataException("找不到用户");
        }
        return userEntity;
    }

    @Override
    public UserEntity findUser(String email, String password) {
        UserEntity userEntity;
        try {
            userEntity = userDao.queryUser(email, ApplicationUtil.md5(password));
        } catch (Exception e) {
            throw new SelectDataFromDatabaseException("查询用户失败");
        }
        if (userEntity == null) {
            /* 跑找不到用户异常*/
            throw new CanNotFindDataException("找不到用户");
        }
        return userEntity;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity user = userDao.queryUserByEmail(username);
        if (user == null) {
            /* 跑找不到用户异常*/
            throw new CanNotFindDataException("找不到用户");
        }
        return new CustomUserDetails(user);
    }
}
